package com.wiserun.RestFul.common;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wiserun.RestFul.RestfulAction.ClientAction;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

@Component // 把此类托管给 Spring，不能省略
public class TaskUtils {
    private static final Logger logger = LoggerFactory.getLogger(ClientAction.class);
    HttpClient httpClient = HttpClients.createDefault();//召唤接口调用神器
    /**
     * 调用org接口数据信息
     */
    //@Scheduled(cron = "1 * * * * *") // 每天凌晨1点执行
    @Scheduled(cron = "0 0 6,12,18 * * ?")
    public void getAllOrganization(){
        System.out.println("定时任务");
        HttpResponse execute;
        String result="";
        JSONObject jsonObject=null;
        HttpPost request =new HttpPost("http://127.0.0.1:8080/pncs/getAllOrganization"); //服务器环境
        //HttpPost request =new HttpPost("http://127.0.0.1:8080/getAllOrganization"); //本地环境
        // 浏览器表示
        request.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0");
        // 传输的类型 不正确时会报错
        request.addHeader("Content-Type", "application/json;charset=utf-8");

        //组装请求参数
        JSONObject json= new JSONObject();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String nowdate = df.format(new Date());//当天日期
        //每天更新，更新前一周的内容
        Calendar calendar2 = new GregorianCalendar();
        calendar2.setTime(new Date());
        calendar2.add(calendar2.DATE,1);
        String nextday= df.format(calendar2.getTime());//后一天的日期

        //获取三天前的时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(calendar.DATE,-3);
        String threeDaysAgo= df.format(calendar.getTime());//前三天的日期

        //封装请求参数列表
        json.put("startTime",threeDaysAgo);//三天前开始
        json.put("stopTime",nextday);//截止到第二天天凌晨1点
        json.put("isWithDeleted",false);//删除的数据
        json.put("withDisabled",true);//停用的数据
        //========循环自动加入结束=====
        StringEntity entityParam = new StringEntity(json.toJSONString(),"utf-8");
        request.setEntity(entityParam);
        //执行请求
        try {
            execute = httpClient.execute(request);
            HttpEntity entity = execute.getEntity();
            result= EntityUtils.toString(entity, "GBK");
            //logger.info("本地接口返回的json数据==>"+result);
            jsonObject = JSON.parseObject(result);
            if(jsonObject==null){
                logger.info(nowdate+"日，自动同步组织机构信息失败");
                logger.info("失败原因========="+jsonObject.toJSONString());
                return;
            }
            if(jsonObject!=null) {
                if(jsonObject.getString("code")!= null){
                    if(!jsonObject.getString("code").equals("200")){
                        logger.info(nowdate+"日，自动同步组织机构信息失败");
                        logger.info("失败原因========="+jsonObject.toJSONString());
                        return;
                    }
                }
            }
            logger.info(nowdate+"日，自动同步组织机构信息成功"+jsonObject.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(nowdate+"日，自动同步组织机构信息失败");
            logger.info("失败原因========="+jsonObject.toJSONString());
        }
    }

    /**
     * 调用user接口数据信息
     */
    //@Scheduled(cron = "1 * * * * *") // 每天凌晨1点执行
    @Scheduled(cron = "0 0 6,12,18 * * ?")
    public void getUsers(){
        HttpResponse execute;
        String result="";
        JSONObject jsonObject=null;
        HttpPost request =new HttpPost("http://127.0.0.1:8080/pncs/getUsers");
        //HttpPost request =new HttpPost("http://127.0.0.1:8080/getUsers");//本地测试环境
        // 浏览器表示
        request.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0");
        // 传输的类型 不正确时会报错
        request.addHeader("Content-Type", "application/json;charset=utf-8");

        //组装请求参数
        JSONObject json= new JSONObject();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String nowdate = df.format(new Date());//当天日期
        //每天更新，更新前一周的内容
        Calendar calendar2 = new GregorianCalendar();
        calendar2.setTime(new Date());
        calendar2.add(calendar2.DATE,1);
        String nextday= df.format(calendar2.getTime());//后一天的日期

        //获取三天前的时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(calendar.DATE,-3);
        String threeDaysAgo= df.format(calendar.getTime());//前三天的日期

        //封装请求参数列表
        String[] arr= new String[]{"0","1","2"};
        json.put("startTime",threeDaysAgo);//三天前开始
        json.put("stopTime",nextday);//截止到第二天天凌晨1点
        json.put("isWithDeleted",false);//删除的数据
        json.put("withDisabled",true);//停用的数据
        json.put("employType",arr);//雇佣类型
        //========循环自动加入结束=====
        StringEntity entityParam = new StringEntity(json.toJSONString(),"utf-8");
        request.setEntity(entityParam);
        //执行请求
        try {
            execute = httpClient.execute(request);
            HttpEntity entity = execute.getEntity();
            result= EntityUtils.toString(entity, "GBK");
            //logger.info("本地接口返回的json数据==>"+result);
            jsonObject = JSON.parseObject(result);
            if(jsonObject==null){
                logger.info(nowdate+"日，自动同步用户--用户组织机构--用户任职记录信息失败");
                logger.info("失败原因========="+jsonObject.toJSONString());
                return;
            }
            if(jsonObject!=null) {
                if(jsonObject.getString("code")!= null){
                    if(!jsonObject.getString("code").equals("200")){
                        logger.info(nowdate+"日，自动同步用户--用户组织机构--用户任职记录信息失败");
                        logger.info("失败原因========="+jsonObject.toJSONString());
                        return;
                    }
                }
            }
            logger.info(nowdate+"日，自动同步用户--用户组织机构--用户任职记录信息成功"+jsonObject.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(nowdate+"日，自动同步用户--用户组织机构--用户任职记录信息失败");
            logger.info("失败原因========="+jsonObject.toJSONString());
        }
    }
}